/*
 * np_time.c
 *
 *  Created on: Nov 29, 2010
 *      Author: jeff_zheng
 *   Copyright: NetPerform Technology
 */
#include "np_common.h"

void np_time_sleep(uint32_t sec, uint32_t nanosec)
{
	struct timespec ts;
	int err;
	ts.tv_sec = sec;
	ts.tv_nsec = nanosec;
	err = nanosleep(&ts,NULL);
	if(err)
	{
		NP_TRACE("np_time_sleep returned earlier %s",strerror(err));
	}
}


static np_bool g_np_time_loop_enable = np_true;
uint64_t g_np_time_ns;
uint64_t g_np_time_us;
uint64_t g_np_time_ms;
uint64_t g_np_time_sec;

void np_time_update()
{
	struct timeval tv;
	gettimeofday(&tv, NULL);
	g_np_time_sec = tv.tv_sec;
	g_np_time_us = g_np_time_sec* 1000000ULL + tv.tv_usec;
	g_np_time_ns = g_np_time_us* 1000;
	g_np_time_ms = g_np_time_us/ 1000;
}



void* np_time_loop(void* arg)
{
	while(g_np_time_loop_enable)
	{
		np_time_update();
		//sleep 1 us
		np_time_sleep(0,1000);
	}
	return NULL;
}


int np_time_lib_init()
{
	np_time_update();
	pthread_attr_t attr;
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
	pthread_t t;
	if(0!=pthread_create(&t, &attr, np_time_loop, NULL))
	{
		return -1;
	}
	return 0;
}
